<?php
/**
 * 签名
 */
declare(strict_types=1);

namespace app\api\controller;

use think\Controller;

class Signsha extends Controller
{
    public $MAX_ENCRYPT_BLOCK = 245; //RSA最大加密明文大小
    public $MAX_DECRYPT_BLOCK = 256; //RSA最小加密明文大小

    /**
     * 拼接需要签名的内容
     * @param array $data 需签名的字段内容
     * @return string
     */    
    public static function getSign($data)
    {
        $Parameters = [];
        foreach ($data as $k => $v) {
            $Parameters[$k] = $v;
        }
        //按字典序排序参数
        ksort($Parameters);
        $sign = '';
        foreach ($Parameters as $k => $v) {
            $sign .= $k . "=" . $v . "&";
        }
        $sign = '&' . rtrim($sign, '&');
        return $sign;
    }

    /**
     * 公钥加密
     * Author: Tao.
     * @param $pubkey  //公钥
     * @param string $bankCode //银行卡号
     * @return string
     */
    public static function getEncrypt($str, $public_key) {
        //$str是待加密字符串
        $encrypted = '';
        $public_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($public_key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        $output = '';
        while ($str) {
            $input = substr($str, 0, 245);
            $str = substr($str, 245);
            openssl_public_encrypt($input, $encrypted, $public_key);
            $output .= $encrypted;
        }

        $output = base64_encode($output);
        return $output;
    }

    /**
     * 公钥格式化
     */
    public static function formatPubKey($pubKey) {
        $fKey = "-----BEGIN PUBLIC KEY-----\n";
        $len = strlen($pubKey);
        for($i = 0; $i < $len; ) {
            $fKey = $fKey . substr($pubKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey .= "-----END PUBLIC KEY-----";
        return $fKey;
    }
}